package com.atguigu.behavior.interpretor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Stack;

public class Client {

    public static void main(String[] args) throws IOException {
        //表达式
        String expStr = "a+b-c";
        
        //a、b、c对应的值放到operatorMap中
        HashMap<String, Integer> varMap=new HashMap<>();//变量数据
        varMap.put("a",1);
        varMap.put("b",10);
        varMap.put("c",100);

        //对表达式进行解析
        Expression expression = parse(expStr);

        
        //运算结果
        int result = expression.interpreter(varMap);
        System.out.println(result);
    }
    
    
    //定义对表达式进行解析的方法（解析器的核心方法，也可以说是真正的解析器）
    private static Expression parse(String expStr) {
        
        Stack<Expression> stack = new Stack<>();
        char[] charArray = expStr.toCharArray(); 
        Expression left = null; 
        Expression right = null; 
        for (int i = 0; i < charArray.length; i++) { 
        switch (charArray[i]) { 
            case '+': left = stack.pop(); 
                      right = new VariableExpression(String.valueOf(charArray[++i])); 
                      stack.push(new AddExpression(left, right)); 
                      break; 
            case '-': 
                      left = stack.pop(); 
                      right = new VariableExpression(String.valueOf(charArray[++i])); 
                      stack.push(new SubExpression(left, right)); 
                      break; 
            default: 
                      stack.push(new VariableExpression(String.valueOf(charArray[i]))); 
                      break; 
            } 
        }
        Expression expression;
        return expression = stack.pop();
    }
}
